import transaction
from celery.schedules import crontab
from celery.task import periodic_task, task
from stockforecaster.models import Company


@task(ignore_result=True)
def fetch_stock_quotes(company_id):
    '''
    Fetch stock quotes for a given company in the database.
    '''
    transaction.begin()
    company = Company.get_by_id(company_id)
    company.fetch_stock_quotes()
    transaction.commit()
    

@periodic_task(run_every=crontab(minute=0, hour=0))
def fetch_all_stock_quotes():
    '''
    Fetch stock quotes for all companies in the database.
    '''
    companies = Company.query.all()
    for company in companies:
        fetch_stock_quotes(company.id)
